<script>
import Taro from "@tarojs/taro";
import { reactive } from "vue";
import { wxPrePayApi, getUserUuidApi } from "./api";
import { getUserInfo } from "@/utils/storage";
import { useTzRouter } from "@/vhooks/useTzRouter";

export default {
  name: "ReCharge",
  components: {},
  setup() {
    const state = reactive({
      selectedCash: 50,
      isPay4Friend: false,
      phone: "",
      phoneValid: false,
      showTip: false,
      uid: "",
    });
    const { route, EventChannel } = useTzRouter();
    const handleSelect = (num) => {
      state.selectedCash = num;
    };

    const cashItemRender = () => {
      const cashOptions = [10, 20, 50, 100, 200, 500];
      return cashOptions.map((item) => {
        return (
          <tz-view class="cash-item">
            <tz-view
              class={[
                "cash-item-radio",
                state.selectedCash === item ? "selected" : "",
              ]}
              onClick={() => handleSelect(item)}
            >
              {item}
            </tz-view>
          </tz-view>
        );
      });
    };

    // 为好友充值
    const forFirendBtnRender = () => {
      const payForFriend = () => {
        state.isPay4Friend = true;
      };
      if (!state.isPay4Friend) {
        return (
          <tz-button type="primary" onClick={payForFriend}>
            为好友充值
          </tz-button>
        );
      }
    };

    const handlePhoneInvalid = (msg) => {
      Taro.showToast({
        title: msg,
        icon: "none",
        duration: 1000,
      });
      state.showTip = true;
      state.phoneValid = false;
    };

    const fetchUserUid = (phoneNumber) => {
      getUserUuidApi({ phoneNum: phoneNumber })
        .then((res) => {
          state.uid = res.data.uid;
          // 手机号验证通过
          state.phoneValid = true;
        })
        .catch(() => {
          handlePhoneInvalid("该手机号码未注册");
        });
    };

    // 充值手机输入框
    const phoneInputRender = () => {
      const isMobile = (str) => {
        const patrn = /^(1)\d{10}$/; ///^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\d{8}$/;
        return !!patrn.exec(str);
      };
      const onBlur = () => {
        state.phone = state.phone.trim();
        try {
          if (!state.phone) {
            throw new Error("请输入手机号码");
          } else if (!isMobile(state.phone)) {
            throw new Error("手机号码格式有误! 例:13618181818");
          }
        } catch (err) {
          handlePhoneInvalid(err.message);
        }
      };
      const onInput = (e) => {
        state.showTip = false;
        /**
         * NOTE:
         * onInput 中 console.log(state.phone, e.detail.value)
         * state.phone 打印出来获取到的是上一次的值，比如第一次输入获取到的是空字符串
         * e.detail.value 获取到的是已经输入的值
         */
        const phoneNumber = e.detail.value.trim();
        if (phoneNumber.length === 11) {
          if (!isMobile(phoneNumber)) {
            handlePhoneInvalid("手机号码格式有误! 例:13618181818");
            return;
          }
          fetchUserUid(phoneNumber);
        }
      };
      if (state.isPay4Friend) {
        return (
          <tz-cell class="target-phone" title="充值手机">
            <tz-input
              type="number"
              maxlength="11"
              v-model={state.phone}
              placeholder="请输入充值手机号"
              onBlur={onBlur}
              onInput={onInput}
              suffixIcon={state.showTip ? "tips" : ""}
            />
          </tz-cell>
        );
      }
    };

    // 微信充值按钮
    const wePayBtnRender = () => {
      const handleWePay = () => {
        // REVIEW: 存在多层嵌套问题
        Taro.login({
          success(loginRes) {
            const params = {
              code: loginRes.code,
              price: state.selectedCash,
            };
            if (state.isPay4Friend) {
              const { name } = getUserInfo();
              params.fUid = state.uid;
              params.descrition = name + "代充值";
            }
            wxPrePayApi(params)
              .then((prePayRes) => {
                const {
                  nonce_str,
                  prepay_id,
                  sign,
                  timestamp,
                } = prePayRes.data;
                Taro.requestPayment({
                  nonceStr: nonce_str,
                  package: "prepay_id=" + prepay_id,
                  paySign: sign,
                  timeStamp: timestamp,
                  signType: "MD5",
                  success() {
                    Taro.redirectTo({
                      url: "/pages/subUser/bill/index",
                    });
                  },
                  fail(err) {
                    console.log(err);
                    Taro.showToast({
                      title: err.errMsg.indexOf("cancel")
                        ? "取消支付"
                        : err.errMsg,
                      icon: "none",
                      duration: 1000,
                    });
                  },
                });
              })
              .catch((err) => {
                console.log(err);
                Taro.showToast({
                  title: err.msg,
                  icon: "none",
                  duration: 1000,
                });
              });
          },
        });
      };

      return (
        <tz-button
          disabled={state.isPay4Friend && !state.phoneValid}
          type="success"
          onClick={handleWePay}
        >
          微信充值
        </tz-button>
      );
    };

    return () => {
      return (
        <tz-view class="recharge">
          <tz-view class="select-board">
            {phoneInputRender()}
            <tz-view class="cash-area">{cashItemRender()}</tz-view>
            <tz-cell class="show-cash" title="充值金额（￥）">
              {state.selectedCash}
            </tz-cell>
          </tz-view>
          {wePayBtnRender()}
          {forFirendBtnRender()}
        </tz-view>
      );
    };
  },
};
</script>

<style lang="scss">
.recharge {
  display: flex;
  align-items: center;
  flex-direction: column;
  background-color: $white;
  padding-bottom: 20px;
  .select-board {
    width: 345px;
    margin-top: 20px;
    .cash-area {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      .cash-item {
        width: 50%;
        padding: 0 10px 10px 10px;
        .cash-item-radio {
          border-radius: 16px;
          height: 32px;
          line-height: 32px;
          color: $white;
          text-align: center;
          border: 1px solid $placeholder-color;
          color: $title-color;
          &.selected {
            background: $warning-color-end;
            color: $white;
          }
        }
      }
    }
    .tz-cell {
      padding-left: 10px;
      font-size: 16px;
      .tz-cell-label {
        width: auto;
      }
    }
    .target-phone {
      .tz-cell-label {
        margin-right: 20px;
      }
      .tz-input {
        font-size: 16px;
        .suffix-icon {
          color: $danger-color;
        }
      }
    }
    .show-cash {
      .tz-cell-value {
        color: $text-color;
      }
    }
  }
  .tz-button {
    width: 345px;
    margin-top: 20px;
    height: 44px;
  }
}
</style>
